<template>
  <div class="plan">
    <header class="plan_header">
      <van-search v-model="searchValue" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" />
    </header>
    <main class="plan_main">
      <van-tabs v-model:active="active" @change="onChange">
        <van-tab title="今日计划">
          <section class="plan_list" v-if="currentPlanList.length > 0">
            <Card v-for="item in currentPlanList" :key="item.id">
              <section class="plan_list_item">
                <section class="plan_list_item_content">
                  <span class="plan_list_item_content_title van-ellipsis">{{ item?.title }}</span>
                  <span class="plan_list_item_content_time">开始时间：{{ item?.planStartDate }}
                    {{ item?.planStartTime }}</span>
                  <span class="plan_list_item_content_time">结束时间：{{ item?.planEndDate }} {{ item?.planEndTime }}</span>
                </section>
                <section class="plan_list_item_status">
                  <van-tag plain type="warning" v-if="item?.status === 1">开启</van-tag>
                  <van-tag plain type="success" v-if="item?.status === 2">关闭</van-tag>
                  <span class="plan_list_item_status_text" style="color: #f50;" v-if="item?.priority === 3">高</span>
                  <span class="plan_list_item_status_text" style="color: coral;" v-if="item?.priority === 2">中</span>
                  <span class="plan_list_item_status_text" style="color: forestgreen;"
                    v-if="item?.priority === 1">低</span>
                </section>
                <section class="plan_list_item_action">
                  <van-icon name="delete-o" color="red" @click="handleDeletePlan(item, 0)" />
                </section>
              </section>
            </Card>
          </section>
          <van-empty description="暂无今日计划" v-if="!currentPlanList.length > 0" />
        </van-tab>
        <van-tab title="全部计划">
          <section class="plan_list" v-if="allPlanList.length > 0">
            <Card v-for="item in allPlanList" :key="item.id">
              <section class="plan_list_item" @click="handleLookPlan(item)">
                <section class="plan_list_item_content">
                  <span class="plan_list_item_content_title van-ellipsis">{{ item?.title }}</span>
                  <span class="plan_list_item_content_time">开始时间：{{ item?.planStartDate }} {{ item?.planStartTime }}</span>
                  <span class="plan_list_item_content_time">结束时间：{{ item?.planEndDate }} {{ item?.planEndTime }}</span>
                </section>
                <section class="plan_list_item_status">
                  <van-tag plain type="warning" v-if="item?.status === 1">开启</van-tag>
                  <van-tag plain type="success" v-if="item?.status === 2">关闭</van-tag>
                  <span class="plan_list_item_status_text" style="color: #f50;" v-if="item?.priority === 3">高</span>
                  <span class="plan_list_item_status_text" style="color: coral;" v-if="item?.priority === 2">中</span>
                  <span class="plan_list_item_status_text" style="color: forestgreen;"
                    v-if="item?.priority === 1">低</span>
                </section>
                <section class="plan_list_item_action">
                  <van-icon name="delete-o" color="red" @click="handleDeletePlan(item, 1)" />
                </section>
              </section>
            </Card>
          </section>
          <van-empty description="暂无计划" v-if="!allPlanList.length > 0" />
        </van-tab>
      </van-tabs>
    </main>
    <section class="plan_action">
      <van-button style="width: 90%;" round type="primary" @click="show = true" block>新增计划</van-button>
    </section>
    <section class="block"></section>

    <van-dialog v-model:show="show" title="新增计划" show-cancel-button @confirm="handleConfirm" @cancel="handleCancel">
      <van-form>
        <van-cell-group inset>
          <van-field v-model="formState.title" name="title" label="计划标题" placeholder="请输入计划标题" />
          <van-field type="textarea" v-model="formState.content" name="content" label="计划内容" placeholder="请输入计划内容" />
          <van-field name="priority" label="优先级">
            <template #input>
              <van-radio-group  v-model="formState.priority" direction="horizontal" shape="dot">
                <van-radio  :name="1" icon-size="16px">低</van-radio>
                <van-radio :name="2" icon-size="16px">中</van-radio>
                <van-radio :name="3" icon-size="16px">高</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field v-model="formState.planStartDate" name="planStartDate" label="计划开始日期" placeholder="请选择计划开始日期"
            @click="show1 = true" />
          <van-field v-model="formState.planStartTime" name="planStartTime" label="计划开始时间" placeholder="请选择计划开始时间"
            @click="show2 = true" />
          <van-field v-model="formState.planEndDate" name="planEndDate" label="计划结束日期" placeholder="请选择计划结束日期"
            @click="show3 = true" />
          <van-field v-model="formState.planEndTime" name="planEndTime" label="计划结束时间" placeholder="请选择计划结束时间"
            @click="show4 = true" />
        </van-cell-group>
      </van-form>
    </van-dialog>

    <van-popup v-model:show="show1" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-date-picker :min-date="new Date()" title="请选择计划开始日期" @confirm="handleStartDateConfirm"
        @cancel="show1 = false" />
    </van-popup>
    <van-popup v-model:show="show2" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-time-picker :columns-type="['hour', 'minute','second']" title="请选择计划开始时间" @confirm="handleStartTimeConfirm"
        @cancel="show2 = false" />
    </van-popup>
    <van-popup v-model:show="show3" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-date-picker :min-date="new Date()" title="请选择计划结束日期" @confirm="handleEndDateConfirm"
        @cancel="show3 = false" />
    </van-popup>
    <van-popup v-model:show="show4" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-time-picker :columns-type="['hour', 'minute','second']" title="请选择计划结束时间" @confirm="handleEndTimeConfirm"
        @cancel="show4 = false" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { showConfirmDialog, showToast } from 'vant';
import { getPlanList, deletePlan,addPlan } from '@/apis/plan';
import dayjs from 'dayjs';
import Card from '@/components/Card/index.vue';


const router = useRouter();

const searchValue = ref('');

const onCancel = () => {
  searchValue.value = '';
}

const onSearch = async (value) => {
  if (!value) {
    return;
  }
  active.value = 1;
  const res = await getPlanList({
    pageNum: 1,
    pageSize: 999,
    title: value,
  });
  if (res?.code === 200) {
    currentPlanList.value = res?.data?.list;
  }
};


const onChange = (index) => {
  active.value = index;

};

const active = ref(0);
const currentPlanList = ref([]);
const allPlanList = ref([]);


const handleDeletePlan = async (item, index) => {
  showConfirmDialog({
    title: '提示',
    message: '确定要删除学习计划吗？',
  }).then(async () => {
    try {
      active.value = null;
      const res = await deletePlan(item?.id);
      if (res?.code === 200) {
        showToast('删除学习计划成功');
        active.value = index;
        return;
      }
      showToast(res?.msg);

    } catch (error) {
      console.log(error, 'delete-plan-error');

    }

  }).catch(() => {

  });

}

const formState = ref({
  title: "",
  content: "",
  priority: "",
  planStartDate: "",
  planEndDate: "",
  planStartTime: "",
  planEndTime: "",
});

const show = ref(false);
const show1 = ref(false);
const show2 = ref(false);
const show3 = ref(false);
const show4 = ref(false);

const handleStartDateConfirm = ({ selectedValues = [] }) => {
  formState.value.planStartDate = selectedValues?.join('-');
  show1.value = false;
};
const handleStartTimeConfirm = ({ selectedValues = [] }) => {
  formState.value.planStartTime = selectedValues?.join(':');
  show2.value = false;

};

const handleEndDateConfirm = ({ selectedValues = [] }) => {
  formState.value.planEndDate = selectedValues?.join('-');
  show3.value = false;
};
const handleEndTimeConfirm = ({ selectedValues = [] }) => {
  formState.value.planEndTime = selectedValues?.join(':');
  show4.value = false;

};

const handleConfirm =  async() => {
    try {
      active.value = null;
      const res = await addPlan(formState.value);
      if(res?.code === 200){
        showToast('新增学习计划成功');
        if(formState.value.planStartDate === dayjs().format('YYYY-MM-DD') && formState.value.planEndDate === dayjs().format('YYYY-MM-DD')){
          active.value = 0;
          formState.value = {};
          return;
        }
        active.value = 1;
        formState.value = {};
        return;
      }
      showToast(res?.msg);

    } catch (error) {
      console.log(error,'add-plan-error');

    }
};

const handleCancel = () => {
  show.value = false;
  formState.value = {};
};

const handleLookPlan = (item) => {
  router.push(`/plan/detail/${item?.id}`);
};
watch(active, async (newVal) => {
  if (newVal === 0) {
    const res = await getPlanList({
      currentTime: dayjs().format('YYYY-MM-DD'),
      pageNum: 1,
      pageSize: 999
    });
    if (res?.code === 200) {
      currentPlanList.value = res?.data?.list;

    }
    return;
  }
  const res = await getPlanList({
    pageNum: 1,
    pageSize: 999
  });
  allPlanList.value = res?.data?.list;
}, { immediate: true })

</script>

<style lang="less" scoped>
.plan {
  &_content {
    box-sizing: border-box;
    padding: 8px;
    margin: 0 auto;
    width: 90%;
  }

  &_list {
    box-sizing: border-box;
    padding: 8px;
    width: 99%;
    margin: 0 auto;

    &_item {
      height: 72px;
      box-sizing: border-box;
      padding: 8px;
      display: flex;
      justify-content: space-evenly;

      &_content {
        width: 190px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;

        &_title {
          font-size: 14px;
          color: #333;
        }

        &_time {
          font-size: 12px;
          color: #999;
        }
      }

      &_status {
        width: 80px;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-evenly;

        &_text {
          font-size: 12px;
        }
      }

      &_action {
        width: 60px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }

  &_action {
    width: 100%;
    height: 32px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 60px;
    left: 0;
  }
}

.block {
  height: 160px;
  width: 100%;
}
</style>
